<template>
  <div>
    <el-table-form ref="form" :model="form">
      <el-form-item label="来电号码:" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入来电号码" clearable />
      </el-form-item>
      <el-form-item label="订单编号:" prop="taskCode">
        <el-input v-model="form.taskCode" placeholder="请输入客户编号" clearable />
      </el-form-item>
      <el-form-item label="客户编号:" prop="csmCode">
        <el-input v-model="form.csmCode" placeholder="请输入客户编号" clearable />
      </el-form-item>
      <el-form-item label="来电时间:" :table-form-merge="2">
        <el-date-picker
          v-model="form.startDt"
          type="datetimerange"
          class="date"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="接听状态:">
        <el-select v-model="form.callStatus" placeholder="请选择" clearable>
          <el-option
            v-for="item in settlesStatusList"
            :key="item.callStatus"
            :label="item.statusName"
            :value="item.callStatus"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接听人:">
        <el-select v-model="form.answerId" placeholder="请选择" clearable>
          <el-option
            v-for="item in answerList"
            :key="item.answerId"
            :label="item.accountName"
            :value="item.answerId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属企业:">
        <el-select v-model="form.corpCode" placeholder="请选择" clearable>
          <el-option
            v-for="item in cropList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </template>
    </el-table-form>
    <div class="exportBtn">
      <el-button v-permission="3" icon="el-icon-download" @click="exportTableData">导出</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:15}"
      border
      stripe
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <call-details
      ref="callDetails"
      :call-details="callDetailsList"
      :pbx-url="pbxUrl"
    />
  </div>
</template>

<script>

  import { parseTime, formatColumnMap } from '@/utils'
  import callDetails from './callDetails.vue'
  import { queryCallRecordInfo, transactor, getCompanyCode, phoneDetail, callExport, selectPlatformSetting, getExportAddress } from '@/api'
  export default {
    name: 'incoming-call',
    components: { callDetails },
    data() {
      return {
        form: {
          phone: null, // 电话号码
          csmCode: null, // 客户编号
          startDt: [],
          callStatus: null, // 接听状态
          answerId: null, // 接听人
          corpCode: null, // 所属企业
          taskCode: ''
        },
        answerList: [], // 接听人下拉框
        cropList: [],
        pbxUrl: '',
        callDetailsList: {},
        settlesStatusList: [
          { callStatus: 1,
            statusName: '正常' },
          { callStatus: 2,
            statusName: '占线  ' },
          { callStatus: 3,
            statusName: '未接听' },
          { callStatus: 4,
            statusName: '通话中' }
        ],
        formData: {},
        tableData: {
          data: [],
          total: 0,
          column: [
            {
              prop: 'callCode',
              label: '来电编号',
              minWidth: 140
            },
            {
              prop: 'phone',
              label: '来电号码',
              minWidth: 110
            },
            {
              prop: 'taskCode',
              label: '关联订单',
              minWidth: 100
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              minWidth: 100
            },
            {
              prop: 'csmName',
              label: '客户名称',
              minWidth: 80
            },
            {
              prop: 'corpName',
              label: '所属企业',
              minWidth: 190,
              render: (h, { row }) => <span>{ (row.corpCode || '') && formatColumnMap(this.cropList, 'value', Number(row.corpCode), 'desc') }</span>
            },
            {
              prop: 'startDt',
              label: '来电时间',
              minWidth: 160,
              render: (h, { row }) => <span>{ row.startDt ? parseTime(row.startDt) : '' }</span>
            },
            {
              prop: 'num',
              label: '坐席号',
              minWidth: 80
            },
            {
              prop: 'answer',
              label: '接听人',
              minWidth: 120
            },
            {
              prop: 'callStatus',
              label: '接听状态',
              formatter: (row) => {
                return row.callStatus === 1 ? '正常' : row.callStatus === 2 ? '占线' : row.callStatus === 3 ? '未接听' : row.callStatus === 4 ? '通话中' : ''
              },
              minWidth: 80
            },
            {
              label: '操作',
              width: 100,
              fixed: 'right',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-button
                      v-permission='2'
                      type='text'
                      onClick={() => this.edit(row, $index)}
                    >
                     查看详情
                    </el-button>
                  </div>
                )
              }
            }
          ]
        }

      }
    },
    created() {
      this.getTime()
      this.getAnswer()
      this.getCompanyCode()
    },
    methods: {
      getTime() {
        const that = this
        const time = []
        const year = new Date().getFullYear()
        const month = new Date().getMonth() + 1
        const nowDate = new Date().getDate()
        const startDt = year + '-' + month + '-' + nowDate + ' 00:00:00'
        const endDt = year + '-' + month + '-' + nowDate + ' 23:59:59'
        time[0] = new Date(startDt).toISOString()
        time[1] = new Date(endDt).toISOString()
        that.$set(that.form, 'startDt', time)
      },
      async getAnswer() {
        const res = await transactor()
        if (res && res.status === 200 && res.data) {
          this.answerList = res.data
        }
      },
      async getCompanyCode() {
        const res = await getCompanyCode()
        if (res && res.status === 200 && res.data) {
          this.cropList = res.data
        }
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          pageIndex: currentPage,
          pageSize: pageSize,
          params: {
            phone: this.form.phone || null,
            startDt: this.form.startDt[0],
            startDtEnd: this.form.startDt[1],
            csmCode: this.form.csmCode || null,
            callStatus: this.form.callStatus,
            answerId: this.form.answerId,
            corpCode: this.form.corpCode,
            taskCode: this.form.taskCode
          }
        }
        if (params.params.corpCode === 0) {
          params.params.corpCode = '00000'
        }
        params.params = JSON.stringify(params.params)
        const res = await queryCallRecordInfo(params)
        if (res && res.status === 200 && res.data) {
          this.tableData.data = res.data.rows
          this.tableData.total = res.data.total
        }
      },
      async exportTableData() {
        this.$confirm('确定导出数据?', '提示', {
          type: 'warning'
        }).then(async() => {
          const baseUrl = await getExportAddress()
          if (baseUrl && baseUrl.data) {
            const params = {
              phone: this.form.phone || null,
              startDt: this.form.startDt[0],
              startDtEnd: this.form.startDt[1],
              csmCode: this.form.csmCode || null,
              callStatus: this.form.callStatus,
              answerId: this.form.answerId,
              corpCode: this.form.corpCode,
              taskCode: this.form.taskCode
            }

            const res = await callExport(params)
            if (res && res.data) {
              const key = res.data.key
              const url = `${baseUrl.data.exportAddress}/page/export/frame?key=${key}`
              window.open(url)
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出'
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.getTime()
        this.form.phone = null
        this.form.csmCode = null
        this.form.callStatus = null
        this.form.answerId = null
        this.form.corpCode = null
        this.form.taskCode = ''
        this.search()
      },
      async edit(row) {
        if (row && row.callId) {
          const res = await phoneDetail({ callId: row.callId })
          if (res && res.status === 200 && res.data) {
            this.callDetailsList = res.data
            const data = await selectPlatformSetting()
            if (data && res.status === 200 && data.data) {
              this.pbxUrl = data.data.pbxurl
            }
            this.$refs.callDetails.open()
          }
        }
      }
    }

  }
</script>

<style>
.el-picker-panel__footer .el-button--text.el-picker-panel__link-btn {
  display: none;
}
.exportBtn {
  margin-bottom: 10px;
}
</style>
